﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace RedesII_WMI
{
    public class WMI_Access
    {
        public List<WMI_Properties> ExecutaQueryWMI(string query, string target, bool target_me)
        {
            ///////////////////////////////////

            ObjectQuery objQuery = new ObjectQuery(query);
            ManagementObjectSearcher searcher = null;

            if (!target_me)
            {
                ConnectionOptions oConn = new ConnectionOptions();

                oConn.Username = "fabio";
                oConn.Password = "12345";
                oConn.EnablePrivileges = true;

                System.Management.ManagementScope oMs = new System.Management.ManagementScope(@"\\" + target + @"\root\cimv2", oConn);
                searcher = new ManagementObjectSearcher(oMs, objQuery);
            }
            else
            {
                searcher = new ManagementObjectSearcher(objQuery);
            }

            ManagementObjectCollection objCollection = searcher.Get();
            if (objCollection.Count > 0)
            {
                List<WMI_Properties> properties = new List<WMI_Properties>();
                WMI_Properties property = null;
                foreach (ManagementObject obj_aux in objCollection)
                {
                    foreach (PropertyData prop_aux in obj_aux.Properties)
                    {
                        property = new WMI_Properties();
                        property._nome = prop_aux.Name;
                        property._valor = (prop_aux.Value != null) ? prop_aux.Value.ToString() : string.Empty;
                        if (prop_aux.Value != null)
                        {
                            properties.Add(property);
                        }
                    }
                }
                return properties;
            }
            else
                return null;
        }
    }
}
